package com.clr.springboot.service.impl;


import com.clr.springboot.dao.UserMapper;
import com.clr.springboot.entity.User;
import com.clr.springboot.service.UserService;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author 车礼荣
 * @version 1.0
 * Create by 2025/3/19 10:14
 */
@Service
public class UserServiceimpl implements UserService {
    @Autowired()
    private UserMapper userMapper;

    @Override
    public User selectByid(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int addUser(User user) {
        return userMapper.insertSelective(user);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateByPrimaryKeySelective(user);

    }

    @Override
    public int deleteUserById(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<User> selectallUsers(User user) {
        return userMapper.selectAll();
    }

    @Override
    public User login(String name, String password) {
        return userMapper.login(name, password);
    }

    @Override
    public List<User> getUserList() {
        return userMapper.selectAll();
    }

    @Override
    public User FindByid(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int delUser(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }




    //分页查询功能
    public PageInfo<User> getUserByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.selectAll();
        return new PageInfo<>(userList);

    }


    @Override
    public PageInfo<User> findByCondition(String name,  Integer age, Integer pageNum, Integer pageSize) {
        // 1. 构建动态查询条件
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.hasText(name)) {
            criteria.andLike("name", "%" + name + "%"); // 模糊查询
        }
        if (StringUtils.hasText(String.valueOf(age))) {
            criteria.andEqualTo("age", age);
        }
        // 2. 开启分页
        PageHelper.startPage(pageNum, pageSize);

        // 3. 执行查询
        List<User> users = userMapper.selectByExample(example);

        // 4. 封装分页结果
        return new PageInfo<>(users);
    }

//查询单个用户
    @Override
    public User FindByUsername(String username) {
        User user=new User();
        user.setName(username);
        return userMapper.selectOne(user);
    }

    @Transactional
    public void batchDelete(List<Integer> ids) {
         userMapper.batchDelete(ids);
    }


}


